
app.component('editor', {
    props: {
        modelValue: {
            type: String,
            default: ''
        },
        editorConfig:{
            type: Object,
            default: {}
        },
        toolbarConfig:{
            type: Object,
            default: {}
        },
        editorStyle: {
            type: Object,
            default: {}
        },
        mode: {
            type: String,
            default: 'default'
        }
    },
    emits: ['update:modelValue'],
    setup(props, {emit}) {
        const content = Vue.computed({
            get() {
                return props.modelValue
            },
            set(val) {
                emit('update:modelValue', val)
            }
        })

        let editor = null

        Vue.onMounted(function (){
            const { createEditor, createToolbar } = window.wangEditor
            const { deepParse } = window.Surface

            const editorConfig = Object.assign({
                scroll: true,
                onChange(editor) {
                    content.value = editor.getHtml()
                },
                customAlert(s, t){
                    switch (t) {
                        case 'success':
                            ElementPlus.ElMessage.success(s)
                            break
                        case 'info':
                            ElementPlus.ElMessage.info(s)
                            break
                        case 'warning':
                            ElementPlus.ElMessage.warning(s)
                            break
                        case 'error':
                            ElementPlus.ElMessage.error(s)
                            break
                        default:
                            ElementPlus.ElMessage.info(s)
                            break
                    }
                }
            }, deepParse(props.editorConfig))

            const toolbarConfig = Object.assign({}, deepParse(props.toolbarConfig))

            const editor = createEditor({
                selector: '#editor-container',
                html: content.value,
                config: editorConfig,
                mode: props.mode,
            })

            const toolbar = createToolbar({
                editor,
                selector: '#toolbar-container',
                config: toolbarConfig,
                mode: props.mode
            })

        })

        Vue.onBeforeUnmount(() => {
            editor && editor.destroy()
        })

        return {
            editorStyle: props.editorStyle
        }
    },
    template: `<div id="editor—wrapper"><div id="toolbar-container"></div><div id="editor-container" :style="editorStyle"></div></div>`,
})

